<template>
  <div>
    <ZgDialog
      title="拖拽盖章"
      v-model="dialogVisible"
      width="80%"
      top="4vh"
      append-to-body
      :fullscreen="dialogFull"
      @close="closes"
      @ok="onAddOk"
      v-if="dialogVisible"
    >
      <iframe ref="testIframe" :src="sealSrc" class="iframe" @load="onIframeLoad"></iframe>
    </ZgDialog>
  </div>
</template>

<script>

export default {

  data () {
    return {
      dialogVisible: false,
      dialogFull: true,
      sealSrc: '/multUserSign.html',
      pendingFileFlag: null,
      sealSaved: false
    }
  },
  created () {
  },
  mounted () {
    window.addEventListener('message', this.handleSealMessage)
  },
  beforeDestroy () {
    window.removeEventListener('message', this.handleSealMessage)
  },
  watch: {
  },
  methods: {
    openSeal (fileflag) {
      this.sealSaved = false // 每次打开前重置
      this.sealSrc = '/multUserSign.html?t=' + Date.now() // 防止缓存
      this.pendingFileFlag = fileflag
      this.dialogVisible = true
    },
    closes () {
      window.removeEventListener('message', this.handleSealMessage)
      this.dialogVisible = false
    },
    //  iframe 加载后注入 fileflag，通过 JS 调用 iframe 内部的 sxca_ceb.business.loadFile(fileflag)，覆盖原有的调用。
    onIframeLoad () {
      console.log(this.pendingFileFlag, 123)
      if (this.pendingFileFlag) {
        console.log(this.pendingFileFlag, 'pendingFileFlag')
        try {
          const iframe = this.$refs.testIframe
          if (iframe && iframe.contentWindow && iframe.contentWindow.sxca_ceb && iframe.contentWindow.sxca_ceb.business) {
            console.log('注入 fileflag', this.pendingFileFlag)
            iframe.contentWindow.sxca_ceb.business.loadFile(this.pendingFileFlag)
          }
        } catch (e) {
          console.error('注入 fileflag 失败', e)
        }
      }
    },
    handleSealMessage (e) {
      if (e.data && e.data.type === 'sealSaved') {
        this.sealSaved = true
      }
    },
    async onAddOk () {
      if (this.sealSaved) {
        const fileTag = this.pendingFileFlag
        try {
          // 1. 下载PDF
          const downloadRes = await this.$http.capost('/v2/api/serCebSign/downloadBatchFile', { fileFlags: fileTag })
          // 2. 转base64为Blob
          const blob = this.convertBase64UrlToBlob(downloadRes.data, this.pendingFileFlag)
          const pdfName = 'malan-' + this.randomString(12) + '.pdf'
          const file = new File([blob], pdfName, { type: blob.type })
          console.log('下载的文件:', file)
          // 3. 构造formData
          const formData = new FormData()
          formData.append('FileBlod', file)
          formData.append('FileCode', pdfName)
          console.log('formData:', formData)
          // 4. 上传到minio
          const uploadRes = await this.$http.post(
            'zg-system/file/upload',
            formData
          )
          // 5. 处理上传结果
          if (uploadRes.success) {
            console.log('保存成功！', uploadRes.data.imgPath)
            localStorage.setItem('gaizhang_test', uploadRes.data.imgPath)
            if (window.top.__GaiZhangCloses) {
              window.top.__GaiZhangCloses(uploadRes.data.imgPath)
            }
          } else {
            console.log('保存失败！')
          }
        } catch (e) {
          console.error('下载或上传失败', e)
        }
      } else {
        console.log(2)
      }
    }

  }
}
</script>

<style lang="scss"  scoped >
::v-deep ZgDialog {
  // height: 99%;
  //max-height: 99%;
  min-height: 40%;
}
.iframe {
  width: 100%;
  // height: calc(100% - 20px);
  height: 600px;
}
.qzClass {
  font-size: 20px;
  color: rgb(32, 160, 255);
}
</style>
